import 'package:flutter/material.dart';
import 'package:flutter_base_lib/flutter_base_lib.dart';
import 'package:flutter_base_lib/src/ui/load_state/load_empty_view.dart';
import 'package:flutter_base_lib/src/ui/load_state/load_error_view.dart';
import 'package:flutter_base_lib/src/ui/load_state/load_state_parent_view.dart';
import 'package:flutter_base_lib/src/ui/load_state/loading_view.dart';
import 'package:provider/provider.dart';

///封装http通用加载错误页，空白页以及正常显示页UI和逻辑，UI可自定义
class BaseView<T extends BaseCommonViewModel> extends StatefulWidget {
  ///加载成功后显示的页面
  final Widget child;

  ///加载中页面
  final Widget? loadingChild;

  ///数据为空的页面
  final Widget? emptyChild;

  ///请求失败显示的页面
  final Widget? errorChild;

  BaseView({required this.child, this.loadingChild, this.emptyChild, this.errorChild});

  @override
  _BaseViewState<T> createState() => _BaseViewState<T>();
}

class _BaseViewState<T extends BaseCommonViewModel> extends State<BaseView> with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Consumer<T>(
      child: widget.child,
      builder: (BuildContext context, T viewModel, Widget? child) {
        if (viewModel.isSuccess()) {
          return child!;
        } else {
          return FutureBuilder(
            future: viewModel.onLoading(context),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                if (viewModel.isFail()) {
                  ///加载失败
                  return _getErrorWidget(viewModel);
                } else if (viewModel.isEmpty()) {
                  ///数据为空
                  return _getEmptyWidget(viewModel);
                } else {
                  ///加载成功
                  return child!;
                }
              } else {
                ///加载中
                return _getLoadingWidget();
              }
            },
          );
        }
      },
    );
  }

  Widget _getErrorWidget(T viewModel) {
    return LoadStateParentView(
      (widget.errorChild ?? BaseLibPlugin.resConfig.configLoadErrorView() ?? LoadErrorView()),
      _onRefresh(viewModel),
    );
  }

  Widget _getEmptyWidget(T viewModel) {
    return LoadStateParentView(
      (widget.emptyChild ?? BaseLibPlugin.resConfig.configLoadEmptyView() ?? LoadEmptyView()),
      _onRefresh(viewModel),
    );
  }

  Widget _getLoadingWidget() {
    return LoadStateParentView(
      (widget.loadingChild ?? BaseLibPlugin.resConfig.configLoadingView() ?? LoadingView()),
      null,
    );
  }

  ///刷新页面
  VoidCallback _onRefresh(T viewModel) {
    return () {
      viewModel.notifyListeners();
    };
  }

  @override
  bool get wantKeepAlive => true;
}
